<template>
  <customDrawer title="设置快捷操作" ref="customDrawerSetMenuQuick" :widthPx="600" :heightPx="winH" @show="_dialogShow" @confirm="_confirm" :autoHide="false" attach="body" placement="right">
    <template #content>
      <FortenVxetableStatic :data="menuList" :columns="columnList" pkName="id"
                            :searchFieldArr="['name']"
                            searchPlaceholder="搜索菜单名称"
                            :defaultSort="defaultSort"
                            :maxHeight="winH"
                            ref="menuTable"
      ></FortenVxetableStatic>
    </template>
  </customDrawer>
</template>

<script>

import FortenVxetableStatic from "@/components/common/FortenVxetableStatic.vue";
import store from '@/vuex'

export default {
  desc: '设置快捷操作',
  name: 'setMenuQuick',
  props: {
  },
  mounted() {
    this.load()
  },
  data() {
    return {
      menuList: [],
      menuListUser: [],
      winH: window.innerHeight,

      columnList: [
        {field: 'name', title: '菜单', width: 300,  sortable: false},
        {
          field: 'isShow', title: '展示', width: 100, sortable: false,
          editRender: {name: 'ElSwitch'},
          formatter: 'formatSwitch',
          titleHelp: '勾选后，将展现在快捷面板',
          filter: true
        },
        {
          field: 'sortNum',
          title: '展示顺序',
          width: 100,
          sortable: true,
          editRender: {name: 'ElInputNumber', attrs: {min: 0, max: 999}},
          titleHelp: '在快捷面板的显示顺序'
        },
      ],

      defaultSort: {
        field: 'sortNum',
        order: 'asc',
      },

      isAfterInit: false
    }
  },
  computed: {
    cpMenuList() {
       this.menuList.forEach(item => {
        if (item.sortNum == undefined) {
          item.sortNum = 0
        }
        if (item.isShow == undefined) {
          this.$set(item, 'isShow', false)
        }
        if (this.menuListUser != null && this.menuListUser.length > 0 && this.menuListUser.findIndex(menuUser => menuUser.typeKey == item.route) != -1) {
          let findIndex = this.menuListUser.findIndex(menuUser => menuUser.typeKey == item.route)
          this.$set(item, 'isShow', true)
          item.sortNum = this.menuListUser[findIndex].sortNum
        } else {
          this.$set(item, 'isShow', false)
        }
      })
      return this.menuList
    },
    cpVisitedviews() {
      return this.$store.state.tagsView.visitedviews
    }
  },
  watch:{
    //路由变化后
    $route() {
      setTimeout(() => {
        this.saveUserMenu(false, true)
      }, 3000)
    }
  },
  components: {
    FortenVxetableStatic
  },
  methods: {
    _dialog() {
      return this.$refs.customDrawerSetMenuQuick
    },
    _dialogShow() {
    },

    // 确认
    _confirm() {
      let list = this.menuList.filter(item => item.isShow)
      this.utilMessage.confirm('确定保存快捷方式调整？', () => {
        this._save(list)
      })
    },

    // 保存
    _save(list) {
      this.utilVue.loadShow(true)
      let index = 1
      let listSave = []
      if (list) {
        list.forEach(item => {
          if (item.sortNum == undefined || item.sortNum == 0) {
            item.sortNum = index
          }
          listSave.push(
            {
              menuId: item.id,
              sortNum: item.sortNum,
            }
          )
          index += 10
        })
      }

      this.$ajax.post('/upms/shortcuts/batchSaveMenu', listSave).then(resp => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.hide()
          this.$emit('change')
        }
      })
    },
    show() {
      this._dialog().show()
    },
    hide() {
      this._dialog().hide()
    },
    setUserMenuList(list) {
      this.menuListUser = list
      this.menuList.forEach(item => {
        if (item.sortNum == undefined) {
          item.sortNum = 0
        }
        if (item.isShow == undefined) {
          this.$set(item, 'isShow', false)
        }
        if (this.menuListUser != null && this.menuListUser.length > 0 && this.menuListUser.findIndex(menuUser => menuUser.menuId == item.id) != -1) {
          let findIndex = this.menuListUser.findIndex(menuUser => menuUser.menuId == item.id)
          this.$set(item, 'isShow', true)
          item.sortNum = this.menuListUser[findIndex].sortNum
        } else {
          this.$set(item, 'isShow', false)
        }
      })
    },
    // 加载数据
    load() {
      let menuList = JSON.parse(JSON.stringify(this.utilVuex.getNavMenuList()))

      let menuIdList = menuList.filter(item =>   ![1, true].includes(item.isShow)).map(item => {
        return item.id
      })

      menuList = menuList.filter(
        item => {
          let isShow =  [1, true].includes(item.isShow)
            && !menuIdList.includes(item.parentId)
            && 'PAGE' == item.type
            && ![1, true].includes(item.flagApp)
            && this.strings.isNotBlank(item.url)
            && (item.url.indexOf('.vue') != -1 || item.url.indexOf('report') != -1 || item.url.indexOf('html') != -1)

          if (isShow && this.strings.isNotBlank(item.parentIds)) {
            item.parentIds.split(',').forEach(item2 => {
              if (menuIdList.includes(item2)) {
                isShow = false
              }
            })
          }
          return isShow
        }
      )

      menuList.forEach(item => {
        if (item.sortNum == undefined) {
          item.sortNum = 0
        }
      })
      this.menuList = menuList


      // 记录上一次菜单
      let menuLastStr = localStorage.getItem('scp_menu_' + this.utils.getUser().loginKey)
      let menuLast = []
      if (this.strings.isNotBlank(menuLastStr))  {
        menuLast = JSON.parse(menuLastStr)
        menuLast = menuLast.filter(item => this.menuList.findIndex(tmp => tmp.url && tmp.url.indexOf(item.path) != -1) != -1)
        for (let index = menuLast.length - 1; index >= 0; index--) {
          this.$store.dispatch('addVisitedView', menuLast[index])
        }
      }

      // 打开上一次菜单
      let scpMenuLast = localStorage.getItem('scp_menu_last_' + this.utils.getUser().loginKey)
      if (this.strings.isNotBlank(scpMenuLast))  {
        try {
          this.utils.openMenu(scpMenuLast)
        }catch (e){

        }
      }

      setTimeout(() => {
        this.isAfterInit = true
      }, 3000)
    },
    // 记录用户菜单
    saveUserMenu(isTabLengthChange, isRouteChange) {
      if (!this.isAfterInit) {
        return
      }

      let visitedviews = this.$store.state.tagsView.visitedviews
      localStorage.setItem('scp_menu_' + this.utils.getUser().loginKey, JSON.stringify(visitedviews))
      localStorage.setItem('scp_menu_last_' + this.utils.getUser().loginKey, this.$route.path)
    }
  }
}
</script>

<style lang="scss">
</style>
